package algorithm

import (
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"svs/model/request"
)

type RSA struct {
}

func (s *RSA) GenP10(key []byte, certReq request.CertificateRequest) ([]byte, error) {
	block, _ := pem.Decode(key)
	priv, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	template := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName:         certReq.Name,
			Organization:       []string{certReq.Organization},
			OrganizationalUnit: []string{certReq.OrganizationalUnit},
			StreetAddress:      []string{certReq.StreetAddress},
			Province:           []string{certReq.Province},
		},
		SignatureAlgorithm: x509.SHA256WithRSA,
		DNSNames:           []string{"test.example.com"},
		EmailAddresses:     []string{certReq.Email},
	}

	//der转为pem格式
	derBytes, err := x509.CreateCertificateRequest(rand.Reader, &template, priv)

	if err != nil {
		return nil, err
	}
	pemBlock := &pem.Block{
		Type:  "CERTIFICATE REQUEST",
		Bytes: derBytes,
	}
	certPem := pem.EncodeToMemory(pemBlock)
	return certPem, nil
}

// 导入证书时使用，判断各项是否符合要求
func (s *RSA) ParseCertificate(cert []byte) *x509.Certificate {
	certInfo, err := x509.ParseCertificate(cert)
	//有错的时候判断一下是不是pem格式的文件，是pem则转一下der
	if err != nil {

	}
	//1.根证验证有效期
	//2.公钥一致性
	return certInfo
}
